/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.yandex.mergesort;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Neophron
 * @param <E>
 */
public class MergeSort<E extends Comparable<E>> implements Runnable {

    private final List<E> A, B;
    private final int p, r, s;

    MergeSort(List<E> A, int p, int r, List<E> B, int s) {
        this.A = A;
        this.B = B;
        this.p = p;
        this.r = r;
        this.s = s;
    }

    @Override
    public void run() {
        int n = r - p + 1;
        if (n == 1) {
            B.set(s, A.get(p));
        } else {
            List<E> T = new ArrayList<>(n);
            for (int i = 0; i < n; i++) {
                T.add(null);
            }
            int q = (p + r) / 2;
            int qq = q - p + 1;
            Thread t1 = new Thread(new MergeSort<>(A, p, q, T, 0));
            MergeSort t2 = new MergeSort<>(A, q + 1, r, T, qq);
            t1.start();
            t2.run();
            try {
                t1.join();
            } catch (InterruptedException ex) {
            }
            Merge t = new Merge<>(T, 0, qq - 1, qq, n - 1, B, s);
            t.run();
        }
    }

}
